﻿
(function () {
    'use strict';
    var serviceId = 'imageSvc';
    angular.module('app').factory(serviceId, ['$rootScope', 'safeApply', imageSvc]);

    function imageSvc($rootScope, safeApply) {

        var service = {
            loadImages: loadImages,
            images: []
        };

        return service;

        function loadImages() {

            $.ajax({
                url: "http://localhost:2664/api/ImageUpload/get-images",
                type: 'GET',
                contentType: "application/json",
            }).done(onImagesLoadedSucces)
              .error(onImagesLoadedError);
        }

        //#region Internal Methods        

        function onImagesLoadedSucces(data) {
//            console.log(data);
//            data.length = 4;
//            //service.images = data;
//            var delay = 0;
//            for (var i = 0; i < data.length; i++) {
//                {
//
//                    setTimeout((function (image) {
//                        return function () {
//                            safeApply($rootScope, function () {
//                                service.images.push(image);
//                                console.log(i);
//                            });
//                        };
//
//                    })(data[i]), delay);
//
//                    delay += 1000;
//
//                }
//            }

            function stop() {
                clearInterval(interval);
            }

            function addToList(num) {
                    var image = data[num];
                var currentImage =
          '<img alt="Embedded Image" width="100" height="80" ng-src="data:image/png;base64,' + image.ImageBytes + ' />';
                $("#imagesAppend").html("<li>Hello</li>");
                $rootScope.$apply();
                console.log(counter);
                console.log(image);
            }


            var counter = 0;
            var interval = setInterval(function () {
                if (counter >= data.length-1) {
                    stop();
                }
                //addToList(counter);
                service.images.push(data[counter]);
                $rootScope.$apply();
                counter++;
            }, 1000);

            console.log(service.images);
        }

        function onImagesLoadedError(data) {
            console.log(data);
        }
        //#endregion
    }
})();
